package com.homelock.processor;

import com.homelock.constants.LockCmdEnum;
import com.homelock.constants.UnlockAttributeEnum;
import com.homelock.entity.HlDevInfo;
import com.homelock.entity.HlDevUserUnlock;
import com.homelock.service.HlDevInfoService;
import com.homelock.service.HlDevUserUnlockService;
import com.pi.base.util.lang.ByteUtil;
import com.pi.smart.client.ins.comm.domain.BaseWifiCmd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户添加,删除
 */
@CmdMeta(values={LockCmdEnum.ADD_USER,LockCmdEnum.DEL_USER})
@Component
public class ZxLockUserProcessor implements BaseMsgProcessor {
    private static final Logger logger = LoggerFactory.getLogger(ZxLockUserProcessor.class);

    @Autowired
    private HlDevInfoService hlDevInfoService;
    @Autowired
    private HlDevUserUnlockService hlDevUserUnlockService;

    /**
     *  Header	0	4		报文头，详情见2.1
     *  DATA	身份码	4	16		用于校验身份合法性，详情见附录2
     * 	Cmd	        20	1	F1
     * 	DataType	21	1	数据类型	见附录4   04
     * 	Description	22	1	数据描述	见附录4   07
     *
     * 	UserType	23	1	用户类型	见附录4
     * 		0x00 未知用户
     *      * 0x01 指纹用户
     *      * 0x02 密码用户
     *      * 0x03 IC用户
     *      * 0x04 钥匙用户
     *      * 0x05 手机用户
     *      * 0x06 遥控用户
     *      * 0x07 临时用户
     *      * 0x0001~0xFFFF, 0x0000为未知用户
     * 	UserIndex	   24	   2	用户编号	见附录4
     * @param message
     */
    @Override
    public void handle(BaseWifiCmd message) {
        HlDevInfo devInfo = hlDevInfoService.findOneByDevCodeAndStateTrue(message.getDevCode());
        if(null == devInfo){
            logger.info("[振兴锁设备用户handle]查询不到相关设备，devCode=",message.getDevCode());
            return;
        }
        byte[] ins = message.getCmd();
        int userType = ins[3] & 0xFF;
        logger.info("userType:{}",userType);
        if(userType < 0 || userType > 0x07){
            userType = 0;
        }
        byte[] idArray = new byte[2];
        System.arraycopy(ins,4,idArray,0,2);
        int userId = ByteUtil.byteToInt(idArray).intValue();
        HlDevUserUnlock unlock = new HlDevUserUnlock();
        unlock.setUnlockName(String.valueOf(userId));
        unlock.setUnlockId(String.valueOf(userId));
        unlock.setDevId(devInfo.getId());
        unlock.setUnlockType((byte)userType);
        // 振兴锁没有用户概念 用户默认为0
        unlock.setDevUserId(0L);
        // 振兴锁是普通开门方式
        unlock.setUnlockAttribute(UnlockAttributeEnum.NORMAL.getAttribute());
        unlock.setUnlockPhase((byte) 2);

        if(ins[2] == LockCmdEnum.ADD_USER.getCode()){
            hlDevUserUnlockService.insertOrUpdate(unlock);
            logger.info("操作类型：{}，新增锁上用户id：{}",ins[2],unlock.getUnlockId());
        }else{
            hlDevUserUnlockService.deleteByDevIdAndUnlockId(unlock);
            logger.info("操作类型：{}，删除锁上用户id：{}",ins[2],unlock.getUnlockId());
        }
    }
}
